<template>
  <div class="page-container">
    <button class="back-button" @click="goToHome">
      <span class="icon-arrow-left"></span>
      返回首页
    </button>
    
    <div class="header-actions">
      <h1>设备报废</h1>
      <button class="primary-btn" @click="showScrapApplyModal = true">
        <span class="icon-plus"></span> 申请报废
      </button>
    </div>
    
    <p>这里是设备报废页面，您可以处理和管理报废的设备。</p>
    
    <div class="card">
      <div class="search-filter">
        <input 
          type="text" 
          v-model="searchQuery" 
          placeholder="搜索设备或申请人..." 
          class="search-input"
        >
        <select v-model="filterStatus" class="filter-select">
          <option value="">所有状态</option>
          <option value="待审批">待审批</option>
          <option value="已批准">已批准</option>
          <option value="已驳回">已驳回</option>
        </select>
      </div>
      
      <table class="scrap-table">
        <thead>
          <tr>
            <th>报废编号</th>
            <th>设备名称</th>
            <th>设备编号</th>
            <th>申请人</th>
            <th>申请日期</th>
            <th>审批状态</th>
            <th>审批人</th>
            <th>审批日期</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="scrap in filteredScraps" :key="scrap.id" class="table-row">
            <td>{{ scrap.code }}</td>
            <td>{{ scrap.deviceName }}</td>
            <td>{{ scrap.deviceCode }}</td>
            <td>{{ scrap.applicant }}</td>
            <td>{{ scrap.applyDate }}</td>
            <td>
              <span :class="`status-badge ${scrap.statusClass}`">
                {{ scrap.status }}
              </span>
            </td>
            <td>{{ scrap.approver || '-' }}</td>
            <td>{{ scrap.approveDate || '-' }}</td>
            <td class="action-buttons">
              <template v-if="scrap.status === '待审批'">
                <button class="btn-approve" @click="approveScrap(scrap)">批准</button>
                <button class="btn-reject" @click="rejectScrap(scrap)">驳回</button>
              </template>
              <button class="btn-view" @click="viewScrap(scrap)">详情</button>
            </td>
          </tr>
          <tr v-if="filteredScraps.length === 0">
            <td colspan="9" class="no-data">暂无报废记录</td>
          </tr>
        </tbody>
      </table>
      
      <div class="pagination">
        <button 
          class="page-btn" 
          :disabled="currentPage === 1" 
          @click="currentPage--"
        >
          上一页
        </button>
        <span class="page-info">
          第 {{ currentPage }} 页，共 {{ totalPages }} 页
        </span>
        <button 
          class="page-btn" 
          :disabled="currentPage === totalPages" 
          @click="currentPage++"
        >
          下一页
        </button>
      </div>
    </div>
    
    <!-- 申请报废弹窗 -->
    <div v-if="showScrapApplyModal" class="modal-overlay">
      <div class="modal">
        <div class="modal-header">
          <h3>设备报废申请</h3>
          <button class="close-btn" @click="showScrapApplyModal = false">&times;</button>
        </div>
        <div class="modal-body">
          <form class="scrap-form">
            <div class="form-group">
              <label>选择设备 <span class="required">*</span></label>
              <select v-model="currentScrap.deviceId" required @change="updateDeviceInfo">
                <option value="">-- 请选择设备 --</option>
                <option 
                  v-for="device in devices" 
                  :key="device.id" 
                  :value="device.id"
                >
                  {{ device.name }} ({{ device.code }}) - {{ device.status }}
                </option>
              </select>
            </div>
            <div class="form-group">
              <label>报废原因 <span class="required">*</span></label>
              <textarea 
                v-model="currentScrap.reason" 
                rows="4"
                placeholder="请详细描述设备需要报废的原因..."
                required
              ></textarea>
            </div>
            <div class="form-group">
              <label>设备状况</label>
              <select v-model="currentScrap.condition">
                <option value="无法维修">无法维修</option>
                <option value="维修成本过高">维修成本过高</option>
                <option value="已过时">已过时</option>
                <option value="损坏严重">损坏严重</option>
                <option value="其他">其他</option>
              </select>
            </div>
            <div class="form-group">
              <label>预估残值(元)</label>
              <input 
                type="number" 
                v-model="currentScrap.residualValue" 
                placeholder="0.00"
                step="0.01"
                min="0"
              >
            </div>
            <div class="form-group">
              <label>申请人 <span class="required">*</span></label>
              <select v-model="currentScrap.applicantId" required>
                <option value="">-- 请选择申请人 --</option>
                <option 
                  v-for="user in users" 
                  :key="user.id" 
                  :value="user.id"
                >
                  {{ user.name }} ({{ user.department }})
                </option>
              </select>
            </div>
          </form>
        </div>
        <div class="modal-footer">
          <button class="cancel-btn" @click="showScrapApplyModal = false">取消</button>
          <button class="save-btn" @click="submitScrapApplication">提交申请</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'DeviceScrap',
  data() {
    return {
      searchQuery: '',
      filterStatus: '',
      currentPage: 1,
      pageSize: 10,
      showScrapApplyModal: false,
      currentScrap: {
        deviceId: '',
        reason: '',
        condition: '无法维修',
        residualValue: 0,
        applicantId: ''
      },
      // 设备数据
      devices: [
        { id: 1, code: 'DEV-001', name: '笔记本电脑', model: 'ThinkPad X1', status: '正常' },
        { id: 2, code: 'DEV-002', name: '打印机', model: 'HP LaserJet Pro', status: '维修中' },
        { id: 3, code: 'DEV-003', name: '投影仪', model: 'Epson CB-X06', status: '正常' },
        { id: 4, code: 'DEV-004', name: '扫描仪', model: 'Canon DR-C225', status: '已报废' },
      ],
      // 用户数据
      users: [
        { id: 1, name: '张三', department: '研发部' },
        { id: 2, name: '李四', department: '市场部' },
        { id: 3, name: '王五', department: '财务部' },
        { id: 4, name: '赵六', department: '行政部' },
        { id: 5, name: '钱七', department: '设备部' }, // 审批人
      ],
      // 报废记录
      scraps: [
        { 
          id: 1, 
          code: 'SCP-001', 
          deviceId: 4,
          deviceName: '扫描仪',
          deviceCode: 'DEV-004',
          reason: '设备老化严重，多次维修后仍无法正常工作，维修成本过高',
          condition: '无法维修',
          residualValue: 50,
          applicantId: 2,
          applicant: '李四',
          applyDate: '2023-04-20',
          status: '已批准',
          statusClass: 'status-approved',
          approverId: 5,
          approver: '钱七',
          approveDate: '2023-04-22',
          approvalOpinion: '同意报废'
        },
        { 
          id: 2, 
          code: 'SCP-002', 
          deviceId: 2,
          deviceName: '打印机',
          deviceCode: 'DEV-002',
          reason: '频繁卡纸，维修多次效果不佳，建议报废更换新设备',
          condition: '维修成本过高',
          residualValue: 100,
          applicantId: 1,
          applicant: '张三',
          applyDate: '2023-05-18',
          status: '待审批',
          statusClass: 'status-pending',
          approverId: null,
          approver: '',
          approveDate: '',
          approvalOpinion: ''
        }
      ]
    };
  },
  computed: {
    filteredScraps() {
      return this.scraps
        .filter(scrap => 
          (this.searchQuery === '' || 
           scrap.deviceName.includes(this.searchQuery) || 
           scrap.deviceCode.includes(this.searchQuery) ||
           scrap.applicant.includes(this.searchQuery)) &&
          (this.filterStatus === '' || scrap.status === this.filterStatus)
        )
        .slice(
          (this.currentPage - 1) * this.pageSize,
          this.currentPage * this.pageSize
        );
    },
    totalPages() {
      const filteredCount = this.scraps.filter(scrap => 
        (this.searchQuery === '' || 
         scrap.deviceName.includes(this.searchQuery) || 
         scrap.deviceCode.includes(this.searchQuery) ||
         scrap.applicant.includes(this.searchQuery)) &&
        (this.filterStatus === '' || scrap.status === this.filterStatus)
      ).length;
      return Math.ceil(filteredCount / this.pageSize);
    }
  },
  methods: {
    goToHome() {
      this.$router.push('/home');
    },
    updateDeviceInfo() {
      const device = this.devices.find(d => d.id === this.currentScrap.deviceId);
      if (device) {
        this.currentScrap.deviceName = device.name;
        this.currentScrap.deviceCode = device.code;
      }
    },
    submitScrapApplication() {
      // 验证必填项
      if (!this.currentScrap.deviceId || !this.currentScrap.reason || !this.currentScrap.applicantId) {
        alert('请填写必填项');
        return;
      }
      
      // 获取申请人姓名
      const applicant = this.users.find(u => u.id === this.currentScrap.applicantId);
      
      // 创建新报废申请
      const newScrap = {
        id: this.scraps.length + 1,
        code: `SCP-${(this.scraps.length + 1).toString().padStart(3, '0')}`,
        ...this.currentScrap,
        applicant: applicant ? applicant.name : '',
        applyDate: new Date().toISOString().split('T')[0],
        status: '待审批',
        statusClass: 'status-pending',
        approverId: null,
        approver: '',
        approveDate: '',
        approvalOpinion: ''
      };
      
      this.scraps.unshift(newScrap);
      
      // 重置表单并关闭弹窗
      this.resetScrapForm();
      this.showScrapApplyModal = false;
    },
    resetScrapForm() {
      this.currentScrap = {
        deviceId: '',
        reason: '',
        condition: '无法维修',
        residualValue: 0,
        applicantId: ''
      };
    },
    approveScrap(scrap) {
      // 获取当前登录的审批人（这里简化处理，默认使用钱七）
      const approver = this.users.find(u => u.id === 5);
      if (!approver) return;
      
      const index = this.scraps.findIndex(s => s.id === scrap.id);
      if (index !== -1) {
        this.scraps[index].status = '已批准';
        this.scraps[index].statusClass = 'status-approved';
        this.scraps[index].approverId = approver.id;
        this.scraps[index].approver = approver.name;
        this.scraps[index].approveDate = new Date().toISOString().split('T')[0];
        
        // 更新设备状态为已报废
        const deviceIndex = this.devices.findIndex(d => d.id === scrap.deviceId);
        if (deviceIndex !== -1) {
          this.devices[deviceIndex].status = '已报废';
        }
      }
    },
    rejectScrap(scrap) {
      // 获取当前登录的审批人（这里简化处理，默认使用钱七）
      const approver = this.users.find(u => u.id === 5);
      if (!approver) return;
      
      const reason = prompt('请输入驳回原因:');
      if (!reason) return;
      
      const index = this.scraps.findIndex(s => s.id === scrap.id);
      if (index !== -1) {
        this.scraps[index].status = '已驳回';
        this.scraps[index].statusClass = 'status-rejected';
        this.scraps[index].approverId = approver.id;
        this.scraps[index].approver = approver.name;
        this.scraps[index].approveDate = new Date().toISOString().split('T')[0];
        this.scraps[index].approvalOpinion = reason;
      }
    },
    viewScrap(scrap) {
      console.log('查看报废详情:', scrap);
      // 可以实现查看详情的逻辑
    }
  }
};
</script>

<style scoped>
.page-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.header-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 20px 0;
}

.primary-btn {
  background: #2ecc71;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 6px;
  transition: background 0.3s;
}

.primary-btn:hover {
  background: #27ae60;
}

.card {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0,0,0,0.1);
  padding: 20px;
  margin-bottom: 20px;
}

.search-filter {
  display: flex;
  gap: 15px;
  margin-bottom: 20px;
}

.search-input, .filter-select {
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  flex: 1;
  max-width: 300px;
}

.scrap-table {
  width: 100%;
  border-collapse: collapse;
  margin-bottom: 20px;
}

.scrap-table th, .scrap-table td {
  padding: 12px 15px;
  text-align: left;
  border-bottom: 1px solid #eee;
  font-size: 14px;
}

.scrap-table th {
  background: #f8f9fa;
  font-weight: 600;
}

.table-row:hover {
  background: #f9f9f9;
  transition: background 0.2s;
}

.status-badge {
  padding: 3px 8px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
}

.status-pending {
  background: #e8f4fd;
  color: #3498db;
}

.status-approved {
  background: #eafaf1;
  color: #27ae60;
}

.status-rejected {
  background: #fdedeb;
  color: #e74c3c;
}

.action-buttons {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.btn-view, .btn-approve, .btn-reject {
  padding: 4px 8px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 13px;
}

.btn-view {
  background: #e3f2fd;
  color: #1976d2;
}

.btn-approve {
  background: #e8f5e9;
  color: #43a047;
}

.btn-reject {
  background: #ffebee;
  color: #c62828;
}

.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 15px;
  margin-top: 20px;
}

.page-btn {
  padding: 6px 12px;
  border: 1px solid #ddd;
  background: white;
  border-radius: 4px;
  cursor: pointer;
}

.page-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.page-info {
  color: #666;
}

.no-data {
  text-align: center;
  padding: 40px;
  color: #999;
}

/* 弹窗样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0,0,0,0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal {
  background: white;
  border-radius: 8px;
  width: 600px;
  max-width: 90%;
  box-shadow: 0 5px 15px rgba(0,0,0,0.2);
}

.modal-header {
  padding: 15px 20px;
  border-bottom: 1px solid #eee;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.close-btn {
  background: none;
  border: none;
  font-size: 20px;
  cursor: pointer;
  color: #999;
}

.modal-body {
  padding: 20px;
}

.scrap-form {
  display: grid;
  gap: 15px;
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.form-group label {
  font-weight: 500;
  font-size: 14px;
}

.required {
  color: #e74c3c;
}

.form-group input, 
.form-group select,
.form-group textarea {
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.form-group textarea {
  resize: vertical;
}

.modal-footer {
  padding: 15px 20px;
  border-top: 1px solid #eee;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.cancel-btn, .save-btn {
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
  border: 1px solid #ddd;
}

.save-btn {
  background: #3498db;
  color: white;
  border-color: #3498db;
}

.cancel-btn:hover {
  background: #f5f5f5;
}

.save-btn:hover {
  background: #2980b9;
}

/* 继承并复用返回按钮样式 */
.back-button {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 10px 15px;
  background: #3498db;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  transition: all 0.3s;
  margin-right: 20px;
  font-weight: 500;
}

.back-button:hover {
  background: #2980b9;
  transform: translateY(-2px);
}
</style>